package leecode.array.排序算法;

/**
 * @author wangxi created on 2021/3/3 00:07
 * @version v1.0
 *
 * https://leetcode-cn.com/problems/sort-an-array/
 */
public class MergeSort {

    public int[] sortArray(int[] nums) {
        if (nums == null || nums.length <= 0) {
            return new int[0];
        }
        sort(nums, 0, nums.length - 1);
        return nums;
    }

    private void sort(int[] nums, int left, int right) {
        if (nums == null || nums.length <= 0) {
            return;
        }
        if (left >= right) {
            return;
        }
        int mid = left + (right - left)/2;
        sort(nums, left, mid);
        sort(nums, mid + 1, right);
        merge(nums, left, right);
    }

    private void merge(int[] nums, int left, int right) {
        if (left >= right) {
            return;
        }
        int mid = (left + right) / 2;
        // 归并排序只能开辟新的数组
        // 快排的递归也开辟了新的内存空间
        int[] temp = new int[right - left + 1];
        int i = left;
        int j = mid + 1;
        int index = 0;
        while (i <= mid && j <= right) {
            if (nums[i] <= nums[j]) {
                temp[index++] = nums[i++];
            } else {
                temp[index++] = nums[j++];
            }
        }
        while (i <= mid) {
            temp[index++] = nums[i++];
        }
        while (j <= right) {
            temp[index++] = nums[j++];
        }
        for (int p = 0; p < temp.length; p++) {
            nums[p + left] = temp[p];
        }
    }
}
